package com.example.lin.day9_27.utils;


import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitClient {

    private static final class Type {
        public static final MediaType FILE_MEDIA_TYPE = MediaType.parse("application/octet-stream");
    }

    private static final String BASE_URL = "http://192.168.3.100:8080/home/";

    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    private ApiRequestService apiRequestService;
    /**
     * 连接超时时间
     */
    private int CONNECT_TIMEOUT = 15;
    /**
     * 读取数据超时时间
     */
    private int READ_TIMEOUT = 5;
    /**
     * 写出数据超时时间
     */
    private int WRITE_TIMEOUT = 5;


    private RetrofitClient() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                //配置OkHttp 的拦截器
//                .addInterceptor()
                //配置 cookie 缓存 , cookie 其实就是一个有规律的字符串
//                .cookieJar()
                .build();

        retrofit = new Retrofit.Builder()
                //配置OkHttpClient
                .client(okHttpClient)
                //基础服务器地址
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //Gson 转换流
                .addConverterFactory(GsonConverterFactory.create())
                //字符串转换流
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        apiRequestService = retrofit.create(ApiRequestService.class);
    }

    public static ApiRequestService getService() {
        return getClient().apiRequestService;
    }

    public static final RetrofitClient getClient() {
        return Singleton.CLIENT;
    }

    private static final class Singleton {
        static final RetrofitClient CLIENT = new RetrofitClient();
    }
}
